package 回显服务器;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * Created with IntelliJ IDEA.
 * Description:服务器
 * User: lenovo
 * Date: 2022-10-17
 * Time: 21:40
 */
public class UDPEchoServe1 {
    DatagramSocket socket = null;
    //构造方法 指定服务器的端口号
    public UDPEchoServe1(int port) throws SocketException {
        this.socket = new DatagramSocket(port);
    }
    //启动服务器
    public void start() throws IOException {
        System.out.println("启动服务器");
        while(true){
            //1.构建一个数据报来接收数据 byte是返回型参数
            DatagramPacket requstPacket = new DatagramPacket(new byte[4096],4096);
            //接收的数据存储到byte数组里
            socket.receive(requstPacket);
            //把请求转化成字符串,方便打印
            String requst = new String(requstPacket.getData(),0,requstPacket.getLength());
            //2.根据请求计算相应
           String response = process(requst);
            //3.将响应发送到客户端
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),response.getBytes().length,
                    requstPacket.getSocketAddress());
            socket.send(responsePacket);

            //4.打印一个日志,记录当前的情况
            System.out.printf("[%s:%d] req: %s; resp: %s\n",requstPacket.getAddress().toString(),
                    requstPacket.getPort(),requst,response);


        }
    }
//回显
    public String process(String requst) {
        return requst;
    }

    public static void main(String[] args) throws IOException {
        UDPEchoServe1 serve = new UDPEchoServe1(9090);
        serve.start();
    }
}
